<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Common\ProvinceController;
use App\Http\Controllers\Controller;
use App\Models\Delivery;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Validation\Rule;

//门店操作相关    todo    只有系统账号有权限操作门店
class DeliveryController extends Controller
{
    //首页
    function index() {
        $provinces = DB::table('cities')->where('level','province')
            ->pluck('name')->toArray();
        return view('admin.delivery.index',['provinces'=>$provinces]);
    }

    //返回门店列表数据
    function data(Request $request) {
        $model = Delivery::query();
        $where = [];
        if ($title = $request->get('title')) {
            $where[] = ['title','like',$title . '%'];
        }

        if ($province = $request->get('province')) {
            $where[] = ['province','=',$province];
        }
        if ($city = $request->get('city')) {
            $where[] = ['city','=',$city];
        }
        $limit = $request->get('limit') ?? LIMIT;
        if ($request->has('status')) {
            $status = $request->get('status');
            switch ($status) {
                case 0:
                    $model = $model->withTrashed();
                    break;
                case 1:
                    break;
                case 2:
                    $model->onlyTrashed();
            }
        }
        $res = $model->where($where)->orderBy('id','desc')->limit($limit)->paginate();

        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res->total(),
            'data'  => $res->items(),
        ];
        return Response::json($data);
    }

    function create() {
        //获取所有的省
        $province = new ProvinceController();
        $provinces = $province->provinces();
        return view('admin.delivery.create',['provinces' => $provinces]);
    }

    //保存门店
    function store(Request $request) {
        $request->validate([
            'title' =>  ['required',Rule::unique('deliveries')->where(function ($query) use ($request) {
                return $query->where('province',$request->post('province'))
                             ->where('city',$request->post('city'))
                             ->where('district',$request->post('district'));
            })],
            'province'  =>  'required',
            'city'  =>  'required',
            'district'  =>  'required',
            'address'  =>  'required'
        ]);
        try{
            Delivery::create([
                'title'             =>  $request->post('title'),
                'province'          =>  $request->post('province'),
                'city'              =>  $request->post('city'),
                'district'          =>  $request->post('district'),
                'address'           =>  $request->post('address'),
            ]);
            DB::commit();
            return Redirect::to(URL::route('delivery'))->with(['success'=>'添加成功']);
        }catch (Exception $exception){
            return Redirect::back()->withErrors('添加失败');
        }
    }

    function edit($delivery_id) {
        $delivery = Delivery::findOrFail($delivery_id);
        //获取所有的省
        $province = new ProvinceController();
        $provinces = $province->provinces();
        return view('admin.delivery.edit',['delivery'=>$delivery,'provinces'=>$provinces]);
    }

    function update(Request $request,$delivery_id) {
        $request->validate([
            'title' =>  ['required',Rule::unique('deliveries')->where(function ($query) use ($request) {
                return $query->where('province',$request->post('province'))
                    ->where('city',$request->post('city'))
                    ->where('district',$request->post('district'));
            })->ignore($delivery_id)],
            'province'  =>  'required',
            'city'  =>  'required',
            'district'  =>  'required',
            'address'  =>  'required'
        ]);
        try{
            Delivery::where('id',$delivery_id)->update([
                'title'             =>  $request->post('title'),
                'province'          =>  $request->post('province'),
                'city'              =>  $request->post('city'),
                'district'          =>  $request->post('district'),
                'address'           =>  $request->post('address'),
            ]);
            return Redirect::to(URL::route('delivery'))->with(['success'=>'修改成功']);
        }catch (Exception $exception){
            return Redirect::back()->withErrors('修改失败');
        }
    }
    //通过审核门店
    function approve(Request $request) {
        //1、修改门店状态
        Store::where('id',$request->post('id'))->update(['status'=>2]);
        //2、todo    后台创建门店账号用以登录
        $data = [
            'code' => 0,
            'msg'   => '审核通过',
        ];
        return Response::json($data);
    }

    //关闭门店
    function close(Request $request) {
        $delivery_id = $request->post('id');
        Delivery::where('id',$delivery_id)->delete();
        $data = [
            'code' => 0,
            'msg'   => '关闭成功',
        ];
        return Response::json($data);
    }

    //开启关闭的门店
    function open(Request $request) {
        $delivery_id = $request->post('id');
        Delivery::where('id',$delivery_id)->restore();
        $data = [
            'code' => 0,
            'msg'   => '开启成功',
        ];
        return Response::json($data);
    }

    //永久删除门店
    function destroy(Request $request) {
        $delivery_id = $request->post('id');
        Delivery::where('id',$delivery_id)->forceDelete();
        $data = [
            'code' => 0,
            'msg'   => '删除成功',
        ];
        return Response::json($data);
    }

}
